#include "rteeprom.h"
#include <avr/interrupt.h>
#include <stddef.h>
#include <avr/io.h>
#include <avr/wdt.h>

void StoreInt(int location, unsigned int data)
{
	unsigned char savedSREG;

 	while(EECR & 0x02)wdt_reset();

	EEAR = location;								// set address
	EECR |= _BV(EERE);							// set "read enable" bit
	if(EEDR!=data)
	{
    	EEDR = data;								// set data
    	savedSREG = SREG;								// keep setting so it can be restored
    	cli();										// disable interrupts
    	EECR |= _BV(EEMWE);							// set "write enable" bit
    	EECR |= _BV(EEWE);							// set "write" bit
    	SREG = savedSREG;								// restore SREG
	}

 	while(EECR & 0x02)wdt_reset();

	EEAR =location+1 ;
	EECR |= _BV(EERE);							// set "read enable" bit
	if(EEDR!=data>>8)
	{
    	EEDR = data>>8;								// set data
    	savedSREG = SREG;								// keep setting so it can be restored
    	cli();										// disable interrupts
    	EECR |= _BV(EEMWE);							// set "write enable" bit
    	EECR |= _BV(EEWE);							// set "write" bit
    	SREG = savedSREG;								// restore SREG
	}
	EEAR=0;
}

unsigned int ReadInt(int location)
{
 	unsigned int t;
 	while(EECR & 0x02)wdt_reset();
	EEAR = location;								// set address
	EECR |= _BV(EERE);							// set "read enable" bit
	t=EEDR;
	EEAR = location+1;								// set address
	EECR |= _BV(EERE);							// set "read enable" bit
	t|=(unsigned int)EEDR<<8;
	EEAR = 0;
	return t;
}

